package com.controller;

import com.bean.WebsiteVisitor;
import com.bean.anno.LogAnno;
import com.bean.anno.VisitAnno;
import com.mapper.repository.mysql.WebsiteVisitorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@Controller
public class UrlController {

    @Autowired
    private WebsiteVisitorRepository websiteVisitorRepository;


    @VisitAnno(apiName = "前台页面访问 /",flag = true)
    @LogAnno(apiName = "前台页面访问接口")
    @GetMapping("/")
    public String frontIndex(){

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        WebsiteVisitor websiteVisitor =new WebsiteVisitor();
        websiteVisitor.setId(UUID.randomUUID().toString());
        websiteVisitor.setAddr(request.getRemoteAddr());
        websiteVisitor.setUseragent(request.getHeader("User-Agent"));
        websiteVisitor.setSource("前台");
        websiteVisitor.setCreatetime(LocalDateTime.now());

        websiteVisitorRepository.save(websiteVisitor);

        return "front_websiteIndex.html";
    }


    @LogAnno(apiName = "后台页面访问接口")
    @GetMapping("/login")
    public String backendIndex(){

        //当前线程
        //RequestAttributes attributes = RequestContextHolder.getRequestAttributes();

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        WebsiteVisitor websiteVisitor =new WebsiteVisitor();
        websiteVisitor.setId(UUID.randomUUID().toString());
        websiteVisitor.setAddr(request.getRemoteAddr());
        websiteVisitor.setUseragent(request.getHeader("User-Agent"));
        websiteVisitor.setSource("后台");

        websiteVisitor.setCreatetime(LocalDateTime.now());

        websiteVisitorRepository.save(websiteVisitor);

        //return "backend_login.html";
        return "backend_selfLogin.html";
    }


    //通过userAgent 来显示不同的内容
/*    @LogAnno(apiName = "后台页面访问接口")
    @GetMapping("/self")
    public String login(){
        return "login.html";
    }*/

}
